package com.whereta.mq.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.whereta.mq.model.LoginLog;
import com.whereta.mq.service.ILoginLogService;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.StatusLine;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPubSub;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Created by vincent on 15-9-10.
 */
@Component("jedisPubSub")
public class RedisListener extends JedisPubSub {

    @Resource
    private ILoginLogService loginLogService;

    private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(MQListener.class);

    private static final Logger log=Logger.getLogger("RECORD");


    @Value("${getip.baidu.url}")
    private String getIpFromBaiduUrl;


    @Override
    public void onPMessage(String pattern, String channel, String message) {

        try {
            //日志
            if (channel.equals("logs")) {
                JSONObject mqMapMessage = JSON.parseObject(message);
                String type = mqMapMessage.getString("type");
                switch (type) {
                    case "login":
                        //保存登陆日志
                        String account = mqMapMessage.getString("account");
                        String ip = mqMapMessage.getString("ip");
                        String logintime = mqMapMessage.getString("logintime");

                        LoginLog loginLog = new LoginLog();
                        loginLog.setAccount(account);
                        loginLog.setLoginIp(ip);
                        loginLog.setLoginTime(new Date(Long.parseLong(logintime)));


                        //根据ｉｐ获取地区
                        HttpClient client = new HttpClient();
                        client.getHttpConnectionManager().getParams().setSoTimeout(5000);
                        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

                        HttpMethod method = null;
                        try {
                            String url = getIpFromBaiduUrl + ip;

                            method = new GetMethod(url);
                            method.getParams().setContentCharset("UTF-8");


                            client.executeMethod(method);
                            StatusLine statusLine = method.getStatusLine();
                            String responseBody = method.getResponseBodyAsString();
                            log.info(responseBody);
                            if (statusLine.getStatusCode() == 200) {
                                JSONObject jsonObject = JSON.parseObject(responseBody);

                                log.info(jsonObject.toJSONString());

                                loginLog.setDetailAddress(jsonObject.getString("address"));
                                JSONObject contentJsonObject = jsonObject.getJSONObject("content");
                                if (contentJsonObject != null) {
                                    loginLog.setAddress(contentJsonObject.getString("address"));
                                    JSONObject point = contentJsonObject.getJSONObject("point");
                                    if (point != null) {
                                        loginLog.setPointX(point.getBigDecimal("x"));
                                        loginLog.setPointY(point.getBigDecimal("y"));
                                    }
                                    JSONObject address_detailJsonObject = contentJsonObject.getJSONObject("address_detail");
                                    if (address_detailJsonObject != null) {
                                        loginLog.setProvince(address_detailJsonObject.getString("province"));
                                        loginLog.setCity(address_detailJsonObject.getString("city"));
                                        loginLog.setCityCode(address_detailJsonObject.getString("city_code"));
                                    }
                                }
                            }

                        } finally {
                            if (method != null) {
                                method.releaseConnection();
                            }
                        }
                        loginLogService.saveLoginLog(loginLog);
                        break;
                }
            }
        } catch (Exception e) {
            logger.error("Error:", e);
        }
    }
}
